import 'package:flutter/material.dart';

import 'package:get/get.dart';

/// 简单状态管理
class SampleGetXControllerSMHome extends StatefulWidget {
  const SampleGetXControllerSMHome({Key? key}) : super(key: key);

  @override
  _SampleGetXControllDemoState createState() => _SampleGetXControllDemoState();
}

class _SampleGetXControllDemoState extends State<SampleGetXControllerSMHome> {
  @override
  Widget build(BuildContext context) {
    // 通过依赖注入方式实例化的控制器
    final counter = Get.put(CounterController());
    return GetMaterialApp(
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text("GetController简单状态管理"),
        ),
        body: Container(
          padding: EdgeInsets.only(left: 16, right: 16),
          child: ListView(
            children: [
              GetBuilder<CounterController>(
                builder: (controler) {
                  return Text(
                    "count的值为: ${counter.count}",
                    style: TextStyle(fontSize: 20),
                  );
                },
                initState: (controller) {},
                dispose: (controller) {},
              ),
              const SizedBox(
                height: 15,
              ),
              ElevatedButton(
                  onPressed: () {
                    counter.increment();
                  },
                  child: const Text("点击Count++"))
            ],
          ),
        ),
      ),
    );
  }
}

/// 继承于GetxController的类，处理页面逻辑的，
class CounterController extends GetxController {
  /// 定义了该变量为响应式变量，当该变量数值变化时，页面的刷新方法将自动刷新
  var count = 0.obs;

  /// 自增方法
  void increment() {
    ++count;
    // 手动更新
    update();
  }
}
